package com.mm.cloth;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.mm.cloth.adapter.ClothesAdapter;
import com.mm.cloth.model.Clothes;
import com.mm.cloth.model.Match;
import com.mm.cloth.utils.LoginCheckUtil;

import java.util.ArrayList;
import java.util.List;

public class MatchDetailActivity extends AppCompatActivity {

    // UI组件
    private ImageView ivMatchImage;
    private TextView tvTitle;
    private TextView tvDescription;
    private TextView tvCategory;
    private TextView tvLikes;
    private TextView tvViews;
    private TextView tvUsername;
    private TextView tvCreatedAt;
    private RecyclerView rvClothes;
    private Button btnLike;
    private Button btnEdit;
    private Button btnDelete;

    // 数据
    private int matchId;
    private Match match;
    private ClothesAdapter clothesAdapter;
    private List<Clothes> clothesList = new ArrayList<>();
    private boolean isLiked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_match_detail);

        // 获取搭配ID
        matchId = getIntent().getIntExtra("match_id", -1);
        if (matchId == -1) {
            Toast.makeText(this, "搭配不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        initViews();
        setupToolbar();
        setupClothesRecyclerView();
        setupListeners();
        loadMatchDetail();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        ivMatchImage = findViewById(R.id.ivMatchImage);
        tvTitle = findViewById(R.id.tvTitle);
        tvDescription = findViewById(R.id.tvDescription);
        tvCategory = findViewById(R.id.tvCategory);
        tvLikes = findViewById(R.id.tvLikes);
        tvViews = findViewById(R.id.tvViews);
        tvUsername = findViewById(R.id.tvUsername);
        tvCreatedAt = findViewById(R.id.tvCreatedAt);
        rvClothes = findViewById(R.id.rvClothes);
        btnLike = findViewById(R.id.btnLike);
        btnEdit = findViewById(R.id.btnEdit);
        btnDelete = findViewById(R.id.btnDelete);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("搭配详情");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupClothesRecyclerView() {
        clothesAdapter = new ClothesAdapter(this, clothesList);
        rvClothes.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvClothes.setAdapter(clothesAdapter);

        clothesAdapter.setOnClothesClickListener(clothes -> {
            // 点击查看衣物详情
            Intent intent = new Intent(this, ClothesDetailActivity.class);
            intent.putExtra("clothes_id", clothes.getId());
            startActivity(intent);
        });
    }

    private void setupListeners() {
        // 点赞按钮
        btnLike.setOnClickListener(v -> {
            if (!LoginCheckUtil.checkLoginAndRedirect(this, true)) {
                return;
            }
            
            isLiked = !isLiked;
            updateLikeButton();
            
            // 模拟点赞/取消点赞
            int likes = Integer.parseInt(tvLikes.getText().toString());
            if (isLiked) {
                likes++;
                Toast.makeText(this, "点赞成功", Toast.LENGTH_SHORT).show();
            } else {
                likes--;
                Toast.makeText(this, "取消点赞", Toast.LENGTH_SHORT).show();
            }
            tvLikes.setText(String.valueOf(likes));
        });

        // 编辑按钮
        btnEdit.setOnClickListener(v -> {
            if (!LoginCheckUtil.checkLoginAndRedirect(this, true)) {
                return;
            }
            
            // 检查是否是当前用户的搭配
            if (match != null && isCurrentUserMatch()) {
                Intent intent = new Intent(this, EditMatchActivity.class);
                intent.putExtra("match_id", matchId);
                startActivity(intent);
            } else {
                Toast.makeText(this, "只能编辑自己的搭配", Toast.LENGTH_SHORT).show();
            }
        });

        // 删除按钮
        btnDelete.setOnClickListener(v -> {
            if (!LoginCheckUtil.checkLoginAndRedirect(this, true)) {
                return;
            }
            
            // 检查是否是当前用户的搭配
            if (match != null && isCurrentUserMatch()) {
                showDeleteConfirmDialog();
            } else {
                Toast.makeText(this, "只能删除自己的搭配", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadMatchDetail() {
        // 模拟加载搭配详情
        match = getSimulatedMatch(matchId);
        
        if (match != null) {
            // 更新UI
            tvTitle.setText(match.getTitle());
            tvDescription.setText(match.getDescription());
            tvCategory.setText(match.getCategoryName());
            tvLikes.setText(String.valueOf(match.getLikes()));
            tvViews.setText(String.valueOf(match.getViews()));
            tvUsername.setText(match.getUserName());
            tvCreatedAt.setText(match.getCreatedAt());
            
            // 加载搭配图片
            if (match.getImageUrl() != null && !match.getImageUrl().isEmpty()) {
                Glide.with(this)
                        .load(match.getImageUrl())
                        .placeholder(R.drawable.placeholder_clothes)
                        .error(R.drawable.placeholder_clothes)
                        .centerCrop()
                        .into(ivMatchImage);
            }
            
            // 加载搭配中的衣物
            clothesList.clear();
            clothesList.addAll(match.getClothesList());
            clothesAdapter.notifyDataSetChanged();
            
            // 更新编辑和删除按钮的可见性
            updateButtonsVisibility();
        } else {
            Toast.makeText(this, "搭配不存在", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private Match getSimulatedMatch(int matchId) {
        // 模拟数据
        Match match = new Match();
        match.setId(matchId);
        match.setTitle("休闲搭配" + matchId);
        match.setDescription("这是一套适合周末休闲的搭配，简单舒适。");
        match.setCategoryId(1);
        match.setCategoryName("日常");
        match.setLikes(42);
        match.setViews(128);
        match.setImageUrl("https://example.com/match" + matchId + ".jpg");
        match.setCreatedAt("2023-06-01 12:30");
        match.setUserId(1);
        match.setUserName("用户001");
        
        // 添加衣物
        match.addClothes(new Clothes(1, "白色T恤", "上衣", "https://example.com/tshirt1.jpg", "春夏"));
        match.addClothes(new Clothes(3, "蓝色牛仔裤", "裤子", "https://example.com/jeans1.jpg", "四季"));
        match.addClothes(new Clothes(8, "白色运动鞋", "鞋子", "https://example.com/shoes2.jpg", "四季"));
        
        return match;
    }

    private boolean isCurrentUserMatch() {
        // 模拟检查是否是当前用户的搭配
        return true;
    }

    private void updateButtonsVisibility() {
        // 如果是当前用户的搭配，显示编辑和删除按钮
        if (isCurrentUserMatch()) {
            btnEdit.setVisibility(View.VISIBLE);
            btnDelete.setVisibility(View.VISIBLE);
        } else {
            btnEdit.setVisibility(View.GONE);
            btnDelete.setVisibility(View.GONE);
        }
    }

    private void updateLikeButton() {
        if (isLiked) {
            btnLike.setText("已点赞");
            btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_filled, 0, 0, 0);
        } else {
            btnLike.setText("点赞");
            btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0);
        }
    }

    private void showDeleteConfirmDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("删除搭配")
                .setMessage("确定要删除这个搭配吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 模拟删除搭配
                    Toast.makeText(MatchDetailActivity.this, "搭配已删除", Toast.LENGTH_SHORT).show();
                    finish();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 